﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http;
using System.Xml;
using bmapi.HelperClass;
using bmapi.Models.DataEntity;
using bmapi.SQLServerAccess;

namespace bmapi.Controllers
{
    [Route("import")]
    public class ImportDataController : PageController
    {
        private List<SQLCommand> m_cmds = new List<SQLCommand>();//插入语句集合 

        /// <summary>
        /// 数据导入 
        /// </summary> 
        /// <param name="obj"></param>
        [HttpPost]
        public HttpResponseMessage ImportDataPost(dynamic obj)
        {
            User currenUser = GetUserByLoginID(GetCrrentIDByToken());
            if (currenUser == null)
                return AssistFun.toJson(new { status = 201, tip = "不合法用户" });

            int year_moth = DateTime.Now.Year * 100 + DateTime.Now.Month;
            try
            {
                #region
                int isModel = Convert.ToInt32(obj.model);
                int saveModel = Convert.ToInt32(obj.SaveModel);
                string type = obj.type.ToString();
                string brand = obj.brand.ToString();
                string sex = obj.sex.ToString();
                #endregion

                string stylePath = m_buyiRoot + "\\buyiStyle\\" + year_moth;
                if (!Directory.Exists(stylePath))
                    Directory.CreateDirectory(stylePath);
                stylePath += "\\";

                string userPath = m_buyiRoot + "\\buyiUpload\\" + currenUser.login_id;
                DirectoryInfo folder = new DirectoryInfo(userPath);
                int allStyle = folder.GetDirectories().Length;
                int modelnameCount = 0;
                //遍历所有子目录
                foreach (DirectoryInfo item in folder.GetDirectories())
                {
                    m_cmds.Clear();
                    List<string> modelName = null;

                    if (saveModel == 0)
                        modelName = GetModelName(item);//普通模式,遍历prj文件,获得样式名
                    else
                    {
                        //加法模式或减法模式,在model文件内获得样式信息
                        string modelFie = item.FullName + "\\" + item.Name + ".model";
                        modelName = GetModelNamesByXml(modelFie);
                    }
                    //向数据库,插入数据,里面有异常处理    
                    item.MoveTo(stylePath + item.Name);
                    if (!InsertData(item, modelName, isModel, type, brand, sex, saveModel, currenUser))
                    {
                        DirectoryInfo src = new DirectoryInfo(stylePath + item.Name);
                        src.MoveTo(item.FullName);
                    }
                    else
                        modelnameCount += modelName.Count;
                }
                return RespondImportInfo(folder, allStyle, modelnameCount);
            }
            catch (Exception e)
            {
                WriteLog("ImportDataPost", e.Message);
                return AssistFun.toJson(new { status = 201, tip = "错误详情请看日志" + e.Message });
            }
        }

        protected List<string> GetModelName(DirectoryInfo styleDir)
        {
            //样式名
            List<string> files = new List<string>();
            foreach (FileInfo file in styleDir.GetFiles("*.prj"))
            {
                string filename = file.Name;
                files.Add(filename.Substring(0, filename.Length - 4));
            }
            return files;
        }

        /// <summary>
        /// 根据.model文件获取款下的样式
        /// </summary>   
        /// <param name="xmlPath"></param>
        /// <returns></returns>
        private List<string> GetModelNamesByXml(string xmlPath)
        {
            List<string> files = new List<string>();
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(xmlPath);
            //获取xml文件中的样式名
            //获取节点列表 
            XmlNodeList model = xmldoc.SelectNodes("//model");
            foreach (XmlElement ele in model)
            {
                string txt = ele.GetElementsByTagName("name")[0].InnerText;
                if (!string.IsNullOrEmpty(txt))
                    files.Add(txt);
            }
            return files;
        }

        private bool InsertData(DirectoryInfo styleDir, List<string> modelName, int isModel, string type, string brand, string sex, int savemodel, User user)
        {
            DirectoryInfo A4 = new DirectoryInfo(styleDir.FullName + "\\A4");
            try
            {
                int styleid = GetNewSafeID(user.login_id);

                AddCmdForStyle(styleid, isModel, styleDir.Name, type, brand, sex, user.login_id, savemodel);

                AddCmdForModel(user, modelName, styleid, A4);

                if (SQLCommand.ExecTran(m_cmds) > 0)
                    return true;
            }
            catch (Exception e)
            {
                WriteLog("InsertData", e.Message);
            }
            return false;
        }

        /// <summary>
        /// 插入style_tb命令
        /// </summary>
        /// <param name="filenames"></param>
        /// <param name="isModel"></param>
        /// <param name="styleName"></param>
        /// <param name="brand"></param>
        /// <param name="sex"></param>
        private void AddCmdForStyle(int styleId, int isModel, string styleName, string type, string brand, string sex, int login_id, int savemodel)
        {
            SQLCommand sc = new SQLCommand("insert into Style_tb values(@id,@name,@model,@save,@type,@brand,@sex,@styleTime)");
            sc.Add("@id", styleId);
            sc.Add("@name", styleName);
            sc.Add("@model", isModel);
            sc.Add("@save", savemodel);
            sc.Add("@type", type);
            sc.Add("@brand", brand);
            sc.Add("@sex", sex);
            sc.Add("@styleTime", DateTime.Now.Year * 100 + DateTime.Now.Month);
            m_cmds.Add(sc);
        }
        /// <summary>
        /// 插入Model_tb命令
        /// </summary>
        /// <param name="currenUser">当前用户</param>
        /// <param name="styleId">款id</param>
        /// <param name="path">模板文件路径</param>
        private int AddCmdForModel(User currenUser, List<string> modelName, int styleId, DirectoryInfo A4)
        {
            //插入model_tb数据  对应有几个模板文件就有多少条记录 
            SQLCommand sc = null;
            string sql = "insert into Model_tb values(@id,@name,@creater,@time,@img,@sid,@plid,@pod,@state)";
            sc = new SQLCommand(sql);

            for (int i = 0; i < modelName.Count; i++)
            {
                int modelid = GetNewSafeID(currenUser.login_id);

                string imgName = "";

                //获取图片名
                if (A4.Exists)
                {
                    imgName = modelName[i] + ".jpg";
                    if (!File.Exists(A4.FullName + "\\" + imgName))
                    {
                        imgName = modelName[i] + ".png";
                        if (!File.Exists(A4.FullName + "\\" + imgName))
                            imgName = "";
                    }
                }

                sc.Add("@id", modelid);
                sc.Add("@name", modelName[i]);
                sc.Add("@img", imgName);
                sc.Add("@creater", currenUser.login_id);
                sc.Add("@time", DateTime.Now);
                sc.Add("@plid", currenUser.PLID);
                sc.Add("@state", 1);
                sc.Add("@pod", 0);
                sc.Add("@sid", styleId);

                m_cmds.Add(sc);

                TaskCmd(currenUser, modelid);
            }
            return 0;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="currenUser"></param>
        /// <param name="id">根据工序编码判断是MODEL.ID还是ORDER.ID  工序编码<33的就是model.Id </param>
        private void TaskCmd(User currenUser, int id)
        {
            SQLCommand sc = null;
            sc = new SQLCommand("insert into Task_tb values(@id, @userid, @code, @time)");
            sc.Add("@id", id);

            sc.Add("@userid", currenUser.login_id);
            sc.Add("@code", 11);
            sc.Add("@time", DateTime.Now);
            m_cmds.Add(sc);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="folder">文件移动后的用户目录 </param>
        /// <param name="styleCount">总的款式</param>
        /// <param name="modelCount">总的样式</param>
        /// <returns></returns>
        private HttpResponseMessage RespondImportInfo(DirectoryInfo folder, int styleCount, int modelCount)
        {
            int userCount = folder.GetDirectories().Length;
            int failCount = styleCount - userCount;
            if (userCount == 0)
                return AssistFun.toJson(new { status = 200, tip = "成功导入" + styleCount + "个款," + modelCount + "个样式" });
            else
                return AssistFun.toJson(new { status = 201, tip = "还剩" + (userCount == styleCount ? userCount : failCount) + "个款未导入" });
        }

        #region  测试
        [HttpGet, Route("testim")]
        public void Test()
        {
            string imgPath = @"C:\Users\Administrator\Desktop\11\test";

            DeleteFolder(imgPath);

            //int sumLength = imgPath.Length;
            //int s = imgPath.LastIndexOf('\\');
            //int e = imgPath.LastIndexOf('.');
            //string imf = Path.GetFileNameWithoutExtension(imgPath);
            //string path = AssistFun.buyiRoot + "\\buyiUpload\\1123";
            //List<string> imgpath = new List<string>();
            //DirectoryInfo folder = new DirectoryInfo(path);
            //foreach (DirectoryInfo dir in folder.GetDirectories())
            //{
            //    DirectoryInfo a3 = new DirectoryInfo(dir.FullName);
            //    foreach (DirectoryInfo file in a3.GetDirectories())
            //    {
            //        if (file.Name.Contains("A3"))
            //        {
            //            DirectoryInfo a3img = new DirectoryInfo(file.FullName);
            //            foreach (FileInfo f in a3img.GetFiles())
            //            {
            //                imgpath.Add(UrlConvertor(f.FullName));
            //            }
            //        }
            //    }
            //}
            //imf = Path.GetFileNameWithoutExtension(imgpath[0]);

            //urlPath = urlPath.Replace(@"\", @"/");
            //return urlPath;

            //string xmlPath = @"D:\joint\HaiLan\文档\model\test.xml";
            //List<string> files = new List<string>();
            //XmlDocument xmldoc = new XmlDocument();
            //xmldoc.Load(xmlPath);
            ////获取xml文件中的样式名
            ////获取节点列表 
            //XmlNodeList model = xmldoc.SelectNodes("//model");
            //foreach (XmlElement ele in model)
            //{
            //    files.Add(ele.GetElementsByTagName("name")[0].InnerText);
            //}

            //MoveFolder(userPath, @"C:\Users\Administrator\Desktop\2\a");
            //DirectoryInfo folder = new DirectoryInfo(userPath);
            //List<string> dirs = new List<string>();

            //Hashtable ht = new Hashtable();            
            //foreach (var item in folder.GetDirectories())
            //{
            //    dirs.Add(item.Name);
            //    DirectoryInfo filefolder = new DirectoryInfo(item.FullName);
            //    List<string> files = new List<string>();
            //    foreach (var file in filefolder.GetFiles())
            //    {
            //        string filename = file.Name;
            //        files.Add(filename.Substring(0, filename.LastIndexOf(".")));
            //    }
            //    ht.Add(item.Name, files);
            //}
            //List<string> modelName = new List<string>();

            //foreach (DictionaryEntry de in ht)
            //{
            //    modelName = de.Value as List<string>;
            //}
        }
        #endregion
    }
}
